package com.cike.productmanager;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cike.productmanager.adt.ActivityFeedback;
import com.cike.productmanager.util.DataApplication;

public class CheckActivity extends Activity {

	private TextView storenameview;
	private EditText salerStatusText;
	private EditText productStatusEditText;
	private EditText materialStatusEditText;
	private EditText stateeditText;
	
	private CheckBox displayStatuscheckBox;
	private boolean displayStatus;
	
	private LinearLayout photodisplayfeild;
	
	private Button takephotobutton;
	private Button completebutton;
	
	//活动号：ID
	private int activitynum;
	
	//活动顺序
	private int ID;
	
	//存储路径
	private File photodir;
	//照片数量
	private int photonum;
	
	
	
	
	
	
	
	
	//TODO 下次把获取信息加入这里，需要读取已经填过的信息
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.checkactivity);
		
		//使用intent传递来的ID找到store name
		Intent intent=getIntent();
        ID= intent.getIntExtra("ID", 0);
        String storename = ((com.cike.productmanager.adt.AActivity)DataApplication.activityList.get(ID)).getStoreBelong();
		storenameview = (TextView) findViewById(R.id.AStoreTextView);
		
		//填入从上一个intent传递来的ID找到store name
		storenameview.setText(storename);
		
		//获取该活动的活动ID
		activitynum = ((com.cike.productmanager.adt.AActivity)DataApplication.activityList.get(ID)).getID();
		
		salerStatusText = (EditText) findViewById(R.id.salerStatusText);
		productStatusEditText = (EditText) findViewById(R.id.productStatusEditText);
		materialStatusEditText = (EditText) findViewById(R.id.materialStatusEditText);
		stateeditText = (EditText) findViewById(R.id.stateeditText);
		
		displayStatuscheckBox = (CheckBox) findViewById(R.id.displayStatuscheckBox);
		displayStatuscheckBox.setChecked(displayStatus);
		
		takephotobutton = (Button)findViewById(R.id.atakephotobutton);
		completebutton = (Button)findViewById(R.id.acompletebutton);
		
		
		
		takephotobutton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				takephoto();
				
			}
		});
		
		
		//点击完成填写，输出，并且结束本Activity
		completebutton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				output();
				finish();
			}
		});
		
		
		
		photodisplayfeild = (LinearLayout)findViewById(R.id.photodisplayfeild);
		
		
	}
	
	
	@Override
	protected void onResume() {
		super.onResume();
		
		if(photonum!=0){
			photodisplayfeild.removeAllViews();
		}
		
		// 检测SD是否可用
		String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
        	Toast.makeText(getApplicationContext(),"请确认SD卡是否可用!", 2).show();
            return;
        }
		
		
		
		
		
		
		
		//以活动号作为地址末尾文件夹
		photodir = new File(DataApplication.savepath+"ACT/"+String.valueOf(activitynum)+"/Image/");
				
		if(!photodir.exists()){
			photodir.mkdirs();// 创建文件夹
		}
		
		
		File[] photolist = photodir.listFiles();
		photonum = photolist.length;
		
		for(int i=0;i<photonum;i++){
			
			View v = LayoutInflater.from(this).inflate(R.layout.photoview,null);
			
			ImageView iv = (ImageView)v.findViewById(R.id.image);
			
			BitmapFactory.Options options = new BitmapFactory.Options();
            options.inSampleSize = 1;
            Bitmap bm = BitmapFactory.decodeFile(photolist[i].getAbsolutePath(), options);
            iv.setImageBitmap(bm);
			
            //本张图片的路径
            final String index = photolist[i].getAbsolutePath();
            
            v.setOnLongClickListener(new View.OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					
					new AlertDialog.Builder(CheckActivity.this)
					.setTitle("确认")
					.setMessage("确定删除该图片吗？")
					.setPositiveButton("是", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							File delfile = new File(index);
							delfile.delete();
							
							//为了刷新显示图片，重新进入onResume
							onPause();
							onResume();
						}
					})
					.setNegativeButton("否", null)
					.show();
					return false;
				}
			});
            
            
			photodisplayfeild.addView(v);
			
		}
		
	}
	
	
	
	
	
	
	private void takephoto(){
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, 1);
	}
	
	
	
	
	
	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
        	
            Bundle bundle = data.getExtras();
            Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
            FileOutputStream b = null;
            photodir.mkdirs();// 创建文件夹
            
            
            
            Time t=new Time();
            t.setToNow(); // 取得系统时间。
            int year = t.year;
            int month = t.month+1;//一定要+1,因为从0开始数的
            int date = t.monthDay;
            int hour = t.hour;    // 0-23
            int minute = t.minute;
            int second = t.second;
            
            String photoname = String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(date)+"-"+String.valueOf(hour)
            		+"-"+String.valueOf(minute)+"-"+String.valueOf(second);
            
            String fileName = DataApplication.savepath+"ACT/"+String.valueOf(activitynum)+"/Image/"+photoname+".jpg";

            try {
                b = new FileOutputStream(fileName);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 80, b);// 把数据写入文件
                
                
                
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                try {
                    b.flush();
                    b.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            
            
            

            
        }
    }
	
	
	
		//输出
		public void output(){
			
			
			//构造feedback
			(((com.cike.productmanager.adt.AActivity)DataApplication.activityList.get(ID))).setFeedback(
					new ActivityFeedback(activitynum, salerStatusText.getText().toString(), 
							materialStatusEditText.getText().toString(), productStatusEditText.getText().toString(),
							displayStatus,stateeditText.getText().toString()));
			
			
			//生成JSON文件
			((ActivityFeedback)((com.cike.productmanager.adt.AActivity)DataApplication.activityList.get(ID)).getFeedback()).generateJSON();
			//存入数据库
			((ActivityFeedback)((com.cike.productmanager.adt.AActivity)DataApplication.activityList.get(ID)).getFeedback()).saveintoDB();
		}
	

}
